<template>
  <div class="step-list">
    <div v-if="steps.length === 0" class="empty-steps">
      <div class="text-center text-gray-500 py-6">
        <el-icon class="text-3xl text-gray-300 mb-2"><i-ep-plus /></el-icon>
        <p class="text-base font-medium">还没有测试步骤</p>
        <p class="text-sm">点击"导入脚本"开始，或使用"新步骤"手动添加</p>
      </div>
    </div>

    <div v-else class="space-y-2">
      <StepCard
        v-for="step in steps"
        :key="step.stepNumber"
        :step="step"
        :status="getStepStatus(step.stepNumber)"
        :readonly="readonly"
        :show-code="showCode"
        :show-run-button="!isExecuting"
        @select="selectStep"
        @edit="editStep"
        @delete="deleteStep"
        @run="runStep"
      />
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted } from 'vue'
import { useScriptStore } from '../stores/script'
import { useExecutionStore } from '../stores/execution'
import { useRecordingStore } from '../stores/recording'
import { ElMessage, ElMessageBox } from 'element-plus'
import StepCard from './StepCard.vue'

// Element Plus 图标
import {
  Plus as iEpPlus
} from '@element-plus/icons-vue'

const props = defineProps({
  readonly: {
    type: Boolean,
    default: false
  },
  showCode: {
    type: Boolean,
    default: true
  },
  // 新增：是否显示录制步骤
  showRecordingSteps: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['step-selected', 'step-edited', 'step-run'])

const scriptStore = useScriptStore()
const executionStore = useExecutionStore()
const recordingStore = useRecordingStore()

// 计算属性 - 支持录制步骤和脚本步骤的切换显示
const steps = computed(() => {
  if (props.showRecordingSteps) {
    // 录制模式：显示录制步骤（无论是否正在录制）
    return recordingStore.recordingSteps
  } else {
    // 普通模式：显示脚本步骤
    return scriptStore.steps
  }
})

const isExecuting = computed(() => executionStore.isExecuting)
const isRecording = computed(() => recordingStore.isRecording)

// 实时步骤同步监听
let stepAddedHandler = null

onMounted(() => {
  // 监听新步骤添加事件
  stepAddedHandler = (event) => {
    const { step, totalSteps } = event.detail
    console.log('StepList: 收到新步骤', step.name)
    
    // 可以在这里添加视觉效果，比如滚动到最新步骤
    setTimeout(() => {
      scrollToLatestStep()
    }, 100)
  }
  
  if (typeof window !== 'undefined') {
    window.addEventListener('stepAddedToUI', stepAddedHandler)
  }
})

onUnmounted(() => {
  // 清理事件监听器
  if (typeof window !== 'undefined' && stepAddedHandler) {
    window.removeEventListener('stepAddedToUI', stepAddedHandler)
  }
})

// 滚动到最新步骤
const scrollToLatestStep = () => {
  const stepCards = document.querySelectorAll('.step-card')
  if (stepCards.length > 0) {
    const lastStep = stepCards[stepCards.length - 1]
    lastStep.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
  }
}

// 方法
const selectStep = (step) => {
  emit('step-selected', step)
  
  // 触发全局步骤选择事件，供ParameterEditor监听
  if (typeof window !== 'undefined') {
    const stepIndex = steps.value.findIndex(s => s.stepNumber === step.stepNumber)
    const event = new CustomEvent('stepSelected', {
      detail: {
        index: stepIndex,
        step: step
      }
    })
    document.dispatchEvent(event)
  }
}

const editStep = (step) => {
  emit('step-edited', step)
}

const runStep = async (step) => {
  try {
    emit('step-run', step)
  } catch (error) {
    ElMessage.error('运行步骤失败: ' + error.message)
  }
}

const deleteStep = async (step) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除步骤 ${step.stepNumber}: ${step.description} 吗？`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    scriptStore.removeStep(step.stepNumber)
    ElMessage.success('步骤已删除')
  } catch {
    // 用户取消删除
  }
}

const getStepStatus = (stepNumber) => {
  return executionStore.getStepStatus(stepNumber)
}
</script>

<style scoped>
.script-step {
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}

.script-step:hover {
  transform: translateY(-1px);
}

.run-step-btn:hover {
  animation: pulse-green 0.6s ease-out;
}

@keyframes pulse-green {
  0% {
    box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.4);
  }
  100% {
    box-shadow: 0 0 0 8px rgba(34, 197, 94, 0);
  }
}

.step-status-icon {
  transition: all 0.3s ease;
}

.empty-steps {
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
